﻿using System;
using System.Drawing;
using System.IO;
using EfficientlyLazy.PhotoFramer.Entity;
using EfficientlyLazy.PhotoFramer.Repository;

namespace EfficientlyLazy.PhotoFramer.Service
{
    [ServiceFactory]
    internal class PhotoService : IPhotoService
    {
        private readonly IRepository<Photo> _photoRepository;

        public PhotoService(IRepository<Photo> photoRepository)
        {
            _photoRepository = photoRepository;
        }

        public void AddToLocalStore(string filename)
        {
            var image = Image.FromFile(filename);

            var photo = new Photo
                            {
                                DateAdded = DateTime.Now,
                                Filename = Path.GetFileName(filename),
                                RelativeLocation = string.Empty,
                                IncludeOnFrame = false,
                                Height = image.Height,
                                HorizontalResolution = image.HorizontalResolution,
                                PixelFormat = image.PixelFormat.ToString(),
                                RawFormat = image.RawFormat.Guid,
                                VerticalResolution = image.VerticalResolution,
                                Width = image.Width
                            };

            _photoRepository.SaveAndFlush(photo);
        }

        //public void Download(Photo photo, string filename)
        //{
        //    var image = ByteArrayToImage(photo.ImageData);

        //    image.Save(filename, new ImageFormat(photo.RawFormat));
        //}

        //internal static byte[] ImageToByteArray(Image image)
        //{
        //    using (var ms = new MemoryStream())
        //    {
        //        image.Save(ms, image.RawFormat);
        //        return ms.ToArray();
        //    }
        //}

        //internal static Image ByteArrayToImage(byte[] byteArray)
        //{
        //    using (var ms = new MemoryStream(byteArray))
        //    {
        //        var image = Image.FromStream(ms);
        //        return image;
        //    }
        //}
    }
}
